package org.bdware.irs.server.http;

import com.google.gson.Gson;
import org.apache.log4j.Logger;
import org.bdware.irs.backend.servicesImpl.BDGrsStorageRocksDBImpl;
import org.bdware.irs.backend.utils.DOIParser;

import java.util.HashMap;
import java.util.Map;

public class GrsHandler extends RegisterHandler{


    BDGrsStorageRocksDBImpl store;

    static Logger logger = Logger.getLogger(GrsHandler.class);

    public GrsHandler(BDGrsStorageRocksDBImpl store){
        this.store =  store;
    }

    @Override
    public Map<String, String> HandleRequest(Map<String, String> postInfo) {

        logger.info("=====GRS receive info=====");
        logger.info(new Gson().toJson(postInfo));

        Map<String,String> respMap = new HashMap<>();
        String action = postInfo.get("action");
        switch (action){
            case "resolve":
                respMap = handleResolve(postInfo);
                break;
            case "update":
                //TODO 更新前缀信息
                handleUpdate(postInfo);
            default:
                logger.info("error response");
        }
        return respMap;
    }

    //TODO 更新操作
    public Map<String,String> handleUpdate(Map<String,String> reqMap)  {

        Map<String,String> respMap = new HashMap<>();

        return respMap;
    }


    public Map<String,String> handleResolve(Map<String,String> reqMap){
        Map<String,String> respMap = new HashMap<>();
        String identifier;
        if (reqMap.get("identifier") != null){
            identifier = reqMap.get("identifier");
        } else{
            respMap.put("status","0");
            respMap.put("response","identifier not found");
            return respMap;
        }
        try{
            //前缀，补全字段信息，现在前缀的key是prefix/dou.ADMIN
            if(DOIParser.getType(identifier).equals("prefix")){
                identifier = identifier + "/dou.ADMIN";
            }
            if(store.getOrganization(identifier) == null){
                respMap.put("status","0");
                respMap.put("response","not exist");
                return respMap;
            }
            String result = new Gson().toJson(store.getOrganization(identifier).toStateInfoBase());
            respMap = new Gson().fromJson(result,HashMap.class);
        }catch (Exception e){
            e.printStackTrace();
            respMap.put("status","0");
            respMap.put("response","resolve failed: " + e.getMessage());
        }
        return respMap;
    }
}

